<template>
  <div class="login-container">
    <div class="login-main">
      <div class="main-left">
        <img
          class="left-topimg"
          src="../../assets/system_images/login2.png"
          alt=""
        />
        <div>{{ title }}</div>
        <img
          class="left-botimg"
          width="150"
          src="../../assets/system_images/login1.png"
          alt=""
        />
      </div>

      <!-- 登录表单区域 -->
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        auto-complete="on"
        label-position="left"
      >
        <div class="title1">欢迎登录</div>
        <div class="title2">请使用账号密码登录</div>

        <!-- 账号输入框 -->
        <el-form-item prop="username">
          <el-input
            ref="username"
            v-model.trim="loginForm.username"
            type="text"
            maxlength="15"
            auto-complete="off"
            placeholder="账号"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>

        <!-- 密码输入框 -->
        <el-form-item prop="password">
          <el-input
            ref="password"
            v-model.trim="loginForm.password"
            :type="passwordType"
            maxlength="20"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
            <svg-icon
              slot="suffix"
              @click="showPwd"
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </el-input>
        </el-form-item>

        <el-button
          round
          :loading="loading"
          type="primary"
          style="
            width: 100%;
            margin-top: 20px;
            height: 40px;
            letter-spacing: 2px;
          "
          @click.native.prevent="handleLogin"
          >登录</el-button
        >

        <div class="tips">
          <span style="margin-right: 20px"></span>
          <span></span>
        </div>
      </el-form>
    </div>
    <ReModal
      class="create-box"
      width="500px"
      v-if="captchaVisible"
      :visible="captchaVisible"
      title="登录校验"
      :showHidebutton="false"
      :beforeClose="modalOnHide"
      :onHide="modalOnHide"
      :onOk="modalOnOk"
      :isLoading="finallyLoading"
      confirmBtnText="确认"
    >
      <template v-slot:childDom>
        <div class="captcha-box">
          <div class="img-box" v-loading="isResetLoading">
            <img @click="onResetCaptcha" :src="captchaUrl" alt="" />
          </div>
          <el-input
            v-model.trim="imgCaptchaCode"
            style="width: 110px"
            size="small"
            placeholder="请输入验证码"
          />
        </div>
      </template>
    </ReModal>
  </div>
</template>

<script>
const validateUsername = (rule, value, callback) => {
  const val = value.trim(); // 收尾去空
  if (val === "") {
    callback(new Error("请输入账号"));
  } else if (val.length < 5) {
    callback(new Error("账号不能少于5位"));
  } else {
    callback();
  }
};

/**
 * 密码设置 --> 限定为6-20位，必含数字、字母、特殊字符中两类
 */
const validatePass = (rule, value, callback) => {
  const val = value.trim(); // 收尾去空
  if (val === "") {
    callback(new Error("请输入密码"));
  } else if (val.length < 6 || val.length > 20) {
    callback(new Error("密码长度6~20，不允许空格"));
  } else {
    callback();
  }
};
import defaultSettings from "@/settings";
import { getImgCaptchaCode } from "@/api/auth";
import ReModal from "@/components/ReModal/index.vue";

export default {
  name: "Login",
  components: {
    ReModal,
  },
  data() {
    return {
      finallyLoading: false,
      isResetLoading: false,
      imgCaptchaUuid: "",
      imgCaptchaCode: "",
      captchaVisible: false,
      captchaUrl: "",
      loginForm: {
        //登录表单对象
        username: "",
        password: "",
      },
      //用户名和密码校验规则
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" },
          { validator: validateUsername, trigger: "blur" },
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
          { validator: validatePass, trigger: "blur" },
        ],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined, //登录后重定向路由路径
      otherQuery: {},
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  computed: {
    title() {
      return defaultSettings.title;
    },
  },
  methods: {
    //切换密码框显示
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "text";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },

    // 登录操作
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          getImgCaptchaCode()
            .then((res) => {
              const { data } = res;
              const { img, uuid } = data;
              this.captchaUrl = img;
              this.imgCaptchaUuid = uuid;
              this.captchaVisible = true;
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    modalOnHide() {
      this.captchaVisible = false;
      this.captchaUrl = "";
      this.imgCaptchaUuid = "";
      this.imgCaptchaCode = "";
      clearTimeout(this.captchaId);
    },
    modalOnOk() {
      if (this.imgCaptchaCode === "") {
        this.$message.error("请输入验证码");
        return;
      }
      const params = {
        ...this.loginForm,
        imgCaptchaCode: this.imgCaptchaCode,
        imgCaptchaUuid: this.imgCaptchaUuid,
      };
      this.finallyLoading = true;
      this.$store
        .dispatch("user/login", params)
        .then((res) => {
          this.$notify({
            title: "提示",
            message: "登录成功！",
            type: "success",
            duration: 2000,
          });
          this.modalOnHide();
          this.$router.push({
            path: this.redirect || "/",
            query: this.otherQuery,
          });
        })
        .catch((err) => {
          if (err.data.result === 1008) {
            this.onResetCaptcha();
          }
        })
        .finally(() => {
          this.finallyLoading = false;
          clearTimeout(this.captchaId);
        });
    },

    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    onResetCaptcha() {
      if (this.isReset) {
        this.$message.error("刚刚刷新验证码，请不要一直点！");
        return;
      }
      this.imgCaptchaCode = "";
      this.captchaUrl = "";
      this.imgCaptchaUuid = "";
      this.isResetLoading = true;
      this.isReset = true;
      getImgCaptchaCode()
        .then((res) => {
          const { data } = res;
          const { img, uuid } = data;
          this.captchaUrl = img;
          this.imgCaptchaUuid = uuid;
        })
        .finally(() => {
          this.isResetLoading = false;
          this.captchaId = setTimeout(() => {
            this.isReset = false;
          }, 20000);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100%;
  position: relative;
  background-image: url("../../assets/system_images/background.png");
  background-size: cover;

  .login-main {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-radius: 10px;
    background: #ffffff;
    width: 520px;
    height: 370px;
    display: flex;
    box-shadow: 0px 0px 10px 10px rgba(42, 42, 42, 0.05);

    .main-left {
      width: 200px;
      height: 100%;
      background: -webkit-linear-gradient(top, #307eff, #76aaff);
      border-radius: 10px 0 0 10px;
      text-align: center;
      padding-top: 46px;

      .left-topimg {
        width: 60px;
      }

      div {
        font-size: 16px;
        line-height: 70px;
        color: #fff;
      }
    }

    .login-form {
      width: 320px;
      padding: 30px;
      border-radius: 0 10px 10px 0;
      text-align: center;

      .title1 {
        font-size: 22px;
        color: #307eff;
        letter-spacing: 4px;
        line-height: 46px;
      }

      .title2 {
        font-size: 14px;
        line-height: 26px;
        color: #307eff;
        letter-spacing: 2px;
        margin-bottom: 40px;
      }

      .el-input {
        height: 38px;
        background-color: #fff;
        input {
          height: 38px;
        }
      }
      .input-icon {
        height: 39px;
        width: 14px;
        margin-left: 2px;
      }
    }

    .title {
      margin: 0 auto 30px auto;
      text-align: center;
      color: #707070;
    }
  }
}

input:-webkit-autofill {
  background-color: rgb(141, 37, 37) !important;
}

::v-deep .el-radio__label {
  font-size: 13px;
}

.captcha-box {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  .img-box {
    margin-right: 10px;
  }
}
</style>
